package com.zoe.vhr.rediscache;

import cn.hutool.core.date.DateUtil;
import com.zoe.vhr.enums.RedisKeyEnum;
import com.zoe.vhr.model.Menu;
import com.zoe.vhr.service.MenuService;
import com.zoe.vhr.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author Zoe.Zhang
 * @Date: 2021/08/04
 * @Description springboot启动完成后, 加载菜单信息
 */
@Component
public class InitMenuWithRoleConfig implements CommandLineRunner, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(InitMenuWithRoleConfig.class);

    @Autowired
    MenuService menuService;

    @Autowired
    RedisService redisService;

    @Override
    public void run(String... args) throws Exception {
        logger.info("缓存菜单数据====start>{}", DateUtil.date());
        initMenus();
        logger.info("缓存菜单数据====end>{}", DateUtil.date());
    }

    private void initMenus() {
        List<Menu> menus = menuService.listMenusAndRoleId();
        redisService.setCacheObject(RedisKeyEnum.ALL_MENUS.getKey(), menus);
    }

    @Override
    public int getOrder() {
        return 1;
    }

    public void refreshMenu() {
        List<Menu> menus = menuService.listMenusAndRoleId();
        redisService.setCacheObject(RedisKeyEnum.ALL_MENUS.getKey(), menus);
    }
}
